﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

namespace Config.Internal
{
    public class ConfigLoadTool
    {
        public static T LoadConfig<T, F>()
        where T : ConfigBase<F>
        where F : ConfigDataBase
        {
            string fileName = typeof(F).ToString();
            fileName = fileName.Substring(fileName.LastIndexOf('.') + 1);
            fileName = string.Format(ConfigConst.ConfigLoadPath, fileName);

            IFormatter formatter = new BinaryFormatter();
            TextAsset ta = Resources.Load<TextAsset>(fileName);
            T ConfigObj;
            using (Stream stream = new MemoryStream(ta.bytes))
            {
                ConfigObj = formatter.Deserialize(stream) as T;
                ConfigObj.DeserializeDataMember();
            }
            Resources.UnloadAsset(ta);
            return ConfigObj;
        }

        public static ConfigBase LoadConfig(System.Type type)
        {
            string fileName = type.ToString();
            fileName = fileName.Substring(fileName.LastIndexOf('.') + 1);
            fileName = string.Format(ConfigConst.ConfigLoadPath, fileName);
            IFormatter formatter = new BinaryFormatter();
            ConfigBase ConfigObj = null;
            TextAsset ta = Resources.Load<TextAsset>(fileName);
            if (ta != null)
            {
                using (Stream stream = new MemoryStream(ta.bytes))
                {
                    ConfigObj = formatter.Deserialize(stream) as ConfigBase;
                    ConfigObj.DeserializeDataMember();
                }
                Resources.UnloadAsset(ta);
            }
            return ConfigObj;
        }
    }
}

